package io.alexkozlov.jpointfedagent.operator;

import com.fasterxml.jackson.core.JsonProcessingException;
import io.alexkozlov.jpointfedagent.DiscoveryController;
import io.alexkozlov.jpointfedagent.model.crd.ServiceExport;
import io.fabric8.kubernetes.client.Watcher;
import io.fabric8.kubernetes.client.WatcherException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

public class ServiceExportWatcher implements Watcher<ServiceExport> {
    private static final Logger LOGGER = LoggerFactory.getLogger(ServiceExportWatcher.class);
    private final DiscoveryController discoveryController;

    public ServiceExportWatcher(DiscoveryController discoveryController, String clusterName) {
        this.discoveryController = discoveryController;
    }

    @Override
    public void eventReceived(Action action, ServiceExport serviceExport) {
        switch (action) {
            case ADDED:
                LOGGER.info("ServiceExport {}.{} added", serviceExport.getMetadata().getName(), serviceExport.getMetadata().getNamespace());
                try {
                    discoveryController.addServiceExport(serviceExport);
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
                break;
            case DELETED:
                LOGGER.info("ServiceExport {}.{} deleted", serviceExport.getMetadata().getName(), serviceExport.getMetadata().getNamespace());
                try {
                    discoveryController.removeServiceExport(serviceExport);
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
                break;
            default:
                // NOTHING TO DO
        }
    }

    @Override
    public void onClose(WatcherException e) {
        LOGGER.error(e.getMessage(), e);
    }
}
